<style lang="less" scope>
  @import "../assets/css/config.less";
  .flex-row-center{
    display: flex;
    justify-content: center;
  }
  .flex-space-between{
    display: flex;
    justify-content: space-between;
    flex-direction: row;
    align-items: center;
  }
  .verify_code{
    width: 150px;
    margin-left: 20px;
    height: 36px;
  }
  .flex-column{
    display: flex;
    flex-direction: column;
  }
  .flex-row{
    display: flex;
    justify-content: start;
  }
  .user-area{
    border-radius: 4px;
    background-color: @header-bgc;
    width: 100%;
    height: 100%;
    padding: 40px 0 0 0;
    min-height: 500px;
    
    .username{
      line-height: 24px; 
      font-size: 14px;
      width: 80px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap; //文本不换行，这样超出一行的部分被截取，显示...
    }
  }
  .user-area .user-pic{
    position: relative;
    margin: 0px auto;
    width: 70px;
    height: 70px;
    border-radius: 50%;
    // padding: 40px 0 0 0;
    overflow: hidden;
    padding: -2px;
  }
  .index-out{
    padding: 30px 30px;
    min-width: 1210px;
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: start;
  }
  .index-left{
    width: 20%;
    height: 100%;
    max-width: 15.625rem;
    padding: 0px 20px 0 0;
  }
  .index-right{
    width: 80%;
    padding: 20px 15px;
  }
  .user-list{
    margin: 25px auto;
    width: 90%;
  }
  .user-list-bgc{
    width: 100%;
  }
  .user-list-item{
    width: 112px;
    margin: 0 auto;
    padding: 5px 0;
    text-align: left;
    font-size: 14px;
  }
  .user-list-bgc:hover{
    font-size: 14px;
    color: @color2;
    background-color: @hover-bgc;
    cursor: pointer;
  }
  .person{
    width: 80%;
  }
  .font{
    line-height: 45px;
    font-size: 16px;
    text-align: right;
    margin: 0 15px 0 0 ;
  }
  .form{
    width: 320px;
  }
  .form .input{
    line-height: 35px;
    margin: 5px 0;
    height: 35px!important;
    width: 100%!important;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    padding: 0px 15px;
    font-size: 14px;
    cursor: default;
  }
  .form .input:hover{
    border: 1px solid #c0c4cc;
  }
  .form .input:focus{
    border-color: #57a3f3;
    box-shadow: 0 0 4px -0px #57a3f3;
    outline: none;
  }
  .button{
    line-height: 36px;
    background-color: @color1;
    color: @white;
    border-radius: 4px;
    font-size: 14px;
    width: 120px;
    margin: 10px 4px;
    letter-spacing: 2px;
    outline: none;
    border: none;
    cursor: pointer;
  }
  .button:hover{
    background-color: @color2;
  }
  .button:active{
    background-color: @color3;
  }
  .button-back{
    line-height: 36px;
    background-color: #fff;
    color: #606266;
    border-radius: 4px;
    font-size: 14px;
    width: 120px;
    margin: 10px 4px;
    letter-spacing: 2px;
    outline: none;
    border: 1px solid #DCDFE6;
    cursor: pointer;
  }
  .error-msg{
    line-height: 20px;
    height: 25px;
    text-align: left;
    padding: 0 4px;
    color: #ED4014;
  }
  .active{
    color: @color2;
  }
  .change-avatar {
    background-color:rgba(0, 0, 0, 0.6);
    color: #fff;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    // display: flex;
    justify-content: center;
    align-items: center;
    cursor: default;
    display: none;
    &:hover{
      display: flex;
    }
  }
  .avatar{
    background-color: #fff;
  }
  .avatar:hover+.change-avatar{
    display: flex;
  }
</style>
<template>
  <div id="person">
    <div style="position: fixed; top: 0; width: 100%; min-width: 1210px">
      <myheader></myheader>
    </div>
    <div :style="bg" id="content" style="background-color: #fff;min-width: 1210px;margin-top:58px">
      <div class="index-out">
        <div class="index-left">
          <div class="user-area">
            <div class="user-pic">
              <img class="avatar" :src="`../static/pic/avatars/${user.avatar}`" style="width:100%;height:100%" alt="">
              <div class="change-avatar" @click="showChangeAvatar">更换头像</div>
            </div>
            <div class="flex-row" style="margin: 10px 0 0 59px">
              <div class="flex-column" style="text-align: left;font-size:13px;width: 60px">
                <div style="line-height:24px;">用户名：</div>
                <div style="line-height:24px;">权　限：</div>
              </div>
              <div class="flex-column" style="text-align: left;font-weight: 600;margin-left: 10px;width: 30px">
                <div class="username">{{ user.username }}</div>
                <div style="line-height:24px;font-size:13px;">{{ user.userGroup === '0' ? '学生' : user.userGroup == '1' ? '超管' : user.userGroup == '2' ? '助教' : '老师' }}</div>
              </div>
            </div>
            <div class="user-list">
              <div class="user-list-bgc">
                <div class="user-list-item active">个人信息</div>
              </div>
              <div class="user-list-bgc">
                <div class="user-list-item" @click="toMessage">我的消息</div>
              </div>
              <div class="user-list-bgc">
                <div class="user-list-item" @click="toChange">修改密码</div>
              </div>
              <div class="user-list-bgc">
                <div class="user-list-item" @click="toBindEmail">绑定邮箱</div>
              </div>
            </div>
          </div>

        </div>
        <div class="index-right">
          <!-- <div @click="toChange" class="change">
            <a>修改密码</a>
          </div> -->
          <div class="flex-row-center" style="margin-top:40px">
            <div class="flex-column">
              <div class="font">用户名:</div>
              <div class="error-msg"></div>
              <div class="font">学校名称:</div>
              <div class="error-msg"></div>
              <div class="font">学号:</div>
              <div class="error-msg"></div>
              <div class="font">真实姓名:</div>
              <div class="error-msg"></div>
              <div class="font">邮箱:</div>
              <div class="error-msg"></div>
              <div class="font" v-if="modify">验证码:</div>
              <div class="error-msg" v-if="modify"></div>
            </div>
            <div class="flex-column form">
              <input 
                class="input"
                v-model="now_formInline.username" 
                @input="validateMsg('username')" 
                :disabled="!modify" 
                :style="userNameErr==='' ? '' : 'border-color: #ED4014;box-shadow: 0 0 4px -0px #ED4014;'"
                type="text"
                name="username"
              >
              <div v-html="userNameErr" class="error-msg"></div>
              <input 
                class="input" 
                @input="validateMsg('schoolName')"  
                v-model="now_formInline.schoolName" 
                name="schoolName"
                :style="schoolNameErr==='' ? '' : 'border-color: #ED4014;box-shadow: 0 0 4px -0px #ED4014;'" 
                :disabled="!modify" type="text"
              />
              <div v-html="schoolNameErr" class="error-msg"></div>
              <input class="input" @input="validateMsg('stuNo')"  v-model="now_formInline.stuNo" name="stuNo"
              :style="stuNoErr==='' ? '' : 'border-color: #ED4014;box-shadow: 0 0 4px -0px #ED4014;'" :disabled="!modify" type="text">
              <div v-html="stuNoErr" class="error-msg"></div>
              <input class="input" @input="validateMsg('realName')"  v-model="now_formInline.realName" name="realName"
              :style="realNameErr==='' ? '' : 'border-color: #ED4014;box-shadow: 0 0 4px -0px #ED4014;'" :disabled="!modify" type="text">
              <div v-html="realNameErr" class="error-msg"></div> 
              <input 
                class="input"
                v-model="formInline.email" 
                disabled
                type="text"
                name="email"
              >
              <div class="error-msg"></div>

              <div class="flex-space-between" v-if="modify">
                <input 
                  class="input"
                  v-model="now_formInline.verifycode" 
                  @input="validateMsg('verifycode')" 
                  :disabled="!modify" 
                  type="text"
                  name="verifycode"
                  :style="verifycodeErr==='' ? '' : 'border-color: #ED4014;box-shadow: 0 0 4px -0px #ED4014;'"
                >
                <div class="verify_code">
                  <verify-code :email="formInline.email" type="modifyInfo"/>
                </div>
              </div>
              <div v-html="verifycodeErr" v-if="modify" class="error-msg"></div>

              <div class="flex-row">
                <button v-if="!modify" class="button" @click="modify_info()">修改信息</button>
                <button v-if="modify" class="button" @click="handleSubmit()">提交</button>
                <button v-if="modify" class="button-back" @click="info()">取 消</button>
              </div>
              
            </div>
          </div>
          
        </div>
      </div>
      <!-- <Layout id="content" :style="bg" class="bg">
        
      </Layout> -->
    </div>
    <message-box v-if="messageBoxFlag" :options="options" @cancel="cancel" @confirm="confirm"/>
    
    <avatars v-if="showAvatarFlag" @handleclose="closeAvatars"/>
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import header from "../components/header.vue";
import avatars from "../components/avatars.vue";
import verifyCode from '../components/verifyCode';
import messageBox from '../components/message_box';
import {
  modifyUserDetail,
  checkUserDuplicate,
  getUserDetail,
  duplicatStuNo
} from "../api/api";
import validator from '../utils/validator'

const validators = {
  username(value) {
    return /^[\w\u4e00-\u9fa5]{3,10}$/g.test(value)
  },
  email(value) {
    var pattern1 = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    var pattern2 = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})+\.([a-zA-Z]{2,4})$/;
    return pattern1.test(value)||pattern2.test(value)
  },
  realName(value) {
    var pattern = /^[\u4e00-\u9fa5]{2,}$/g;
    return pattern.test(value)
  },
  schoolName(value) {
    return true
  },
  stuNo(value) {
    var pattern = /^\d{7,15}$/g;
    return pattern.test(value)
  },
  verifycode(value) {
    return true
  }
}
const errorMsg = { 
  username: {
    name: '用户名',
    errKey: 'userNameErr', // 错误信息承载变量名
    errmsg: '请输入3-10个字母/汉字/数字/下划线' // 格式校验不通过时返回的错误信息
  }, 
  email: {
    name: '邮箱地址',
    errKey: 'emailErr',
    errmsg: '请输入合法的邮箱地址'
  }, 
  realName: {
    name: '姓名',
    errKey: 'realNameErr',
    errmsg: '请输入2个以上中文字符'
  }, 
  schoolName: {
    name: '学校名称',
    errKey: 'schoolNameErr'
  }, 
  stuNo: {
    name: '学号',
    errKey: 'stuNoErr',
    errmsg: '请输入7到15位数字学号'
  },
  verifycode: {
    name: '验证码',
    errKey: 'verifycodeErr'
  }
}


export default {
  name: "person",
  data: function() {
    return {
      modify: 0,
      userCenterList: [
        {
          name: "个人信息",
          group: ['0', '1', '2', '3'],
          link: 'person'
        }, {
          name: "我的消息",
          group: ['0', '1', '2', '3'],
          link: 'person'
        }, {
          name: "修改密码",
          group: ['0', '1', '2', '3'],
          link: 'person'
        }
        
      ],

      options:{
        title: '提示',
        content: '请先为您的账号绑定邮箱！',
        cancel: '取消',
        confirm: '去绑定'
      },

      messageBoxFlag: false,
      
      bg: {
        width: `${window.innerWidth}px`,
        height: "auto"
      },
      now_formInline: {
        username: "",
        schoolName: "",
        stuNo: "",
        realName: ""
      },
      formInline: {
        username: "",
        schoolName: "",
        stuNo: "",
        realName: "",
        email: "",
        _id: ""
      },
      userNameErr: '',
      emailErr: '',
      schoolNameErr: '',
      stuNoErr: '',
      realNameErr: '',
      verifycodeErr: '',
      errObj: {},
      vali: null,
      showAvatarFlag: false
    };
  },
  components: {
    myheader: header,
    'verify-code': verifyCode,
    'message-box': messageBox,
    avatars
  },
  computed: {
    user: function() {
      return JSON.parse(this.$store.state.user)
    }
  },
  created() {
    this.vali = validator({}, validators, errorMsg, res => {
      if(res.state===false){
        this[res.key] = res.msg
      } else {
        this[res.key] = ''
      }
    })
  },
  mounted() {
    let content_top = document.getElementById("content").offsetTop;
    this.bg.height = `${window.innerHeight - content_top}px`;

    this.getUserDetail();
 },

  methods: {
    ...mapActions([
      'getUserMesAsync'
    ]),
    cancel(){
      this.messageBoxFlag = false;
    },
    confirm(){
      this.$router.push({
        name: 'bindEmail'
      })
    },
    closeAvatars(){
      this.showAvatarFlag = false
    },
    showChangeAvatar() {
      this.showAvatarFlag = true
    },
    getUserDetail(){
      var that = this;
      getUserDetail({
        token: this.$store.state.token,
        UUID: this.$store.state.UUID
      }).then(res => {
        if (process.env.NODE_ENV === "development") {
          console.log(res);
        }

        that.formInline.username = res.username;
        that.formInline.schoolName = res.school;
        that.formInline.stuNo = res.stuNo;
        that.formInline.realName = res.realName;
        that.formInline.email = res.email;

        that.now_formInline.username = res.username;
        that.now_formInline.schoolName = res.school;
        that.now_formInline.stuNo = res.stuNo;
        that.now_formInline.realName = res.realName;

        that.formInline._id = res._id;
      });
  
    },
    validateMsg(attr) {
      this.vali[attr] = this.now_formInline[attr]
    },
    modify_info() {
      if(!this.formInline.email||this.formInline.email.trim()===''){
        this.messageBoxFlag = true;
        return
      }
      this.validateMsg('username');
      this.validateMsg('schoolName');
      this.validateMsg('stuNo');
      this.validateMsg('realName');
      this.validateMsg('verifycode');
      this.modify = 1;
    },
    info() {
      this.modify = 0;
      this.userNameErr = ''
      this.schoolNameErr = ''
      this.realNameErr = ''
      this.stuNoErr = ''
      this.verifycodeErr = ''
      let that = this
      that.now_formInline.username = that.formInline.username;
      that.now_formInline.schoolName = that.formInline.schoolName;
      that.now_formInline.stuNo = that.formInline.stuNo;
      that.now_formInline.realName = that.formInline.realName;
      that.now_formInline.verifycode = '';
    },
    handleSubmit() {
      // return
      if (this.userNameErr || this.schoolNameErr || this.realNameErr || this.stuNoErr || this.verifycodeErr) {
        this.$Message.error("信息不完整");
        return
      }
      duplicatStuNo({
        stuNo: this.now_formInline.stuNo,
        school: this.now_formInline.schoolName,
        UUID: this.$store.state.UUID
      }).then(res => {
        if (res.state === true) {
          this.checkDuplicate = res.duplicate;
          if (!this.checkDuplicate) {
            let form = this.now_formInline;
            var modifyParams = {
              username: form.username,
              stuNo: form.stuNo,
              school: form.schoolName,
              realName: form.realName,
              email: this.formInline.email,
              code: form.verifycode,
              UUID: this.$store.state.UUID,
              // token: this.$store.state.token
            };
            if (process.env.NODE_ENV === "development") {
              console.log(modifyParams);
            }

            modifyUserDetail(modifyParams)
            .then(response => {
              if (response.state === true) {
                this.$Message.success("修改成功");
                this.getUserMesAsync()

                this.$data.now_formInline.username = modifyParams.username;
                this.$data.now_formInline.schoolName = modifyParams.school;
                this.$data.now_formInline.stuNo = modifyParams.stuNo;
                this.$data.now_formInline.realName = modifyParams.realName;
                this.$data.now_formInline.verifycode = '';

                this.$data.formInline.username = modifyParams.username;
                this.$data.formInline.schoolName = modifyParams.school;
                this.$data.formInline.stuNo = modifyParams.stuNo;
                this.$data.formInline.realName = modifyParams.realName;

                this.$data.modify = 0;
              } else {
                this.$Message.error(response.msg);
              }
            })
            .catch(error => {
              this.$Message.error(error.msg);
            });
          } else {
            this.$Message.error("该学号已被注册");
          }
        } else {
          this.$Message.error("修改用户信息失败！");
        }
      }).catch(err => {
        this.$Message.error(err.msg);
      })
      
      
    },
    toBindEmail(){
      this.$router.push("/bindEmail");
    },
    toChange() {
      this.$router.push("/change_pass");
    },
    toMessage(){
      this.$router.push("/message");
    }
  }
};
</script>

<style lang="less" scoped>
.btns {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.person {
  width: 30%;
  padding: 40px;
  margin-top: 60px;
}
.bg {
  padding: 24px 24px;
  position: absolute;
  background: #fff;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}

.change {
  align-self: flex-end;
}
</style>
